// 公共中间件封装

const responseResult = require("../util/responseResult");
const {verifyToken} = require("../util/index");
const {checkParam, getHeaderToken} = require("../util");
const {loginSql} = require("../model/authorModel");

/*
* 验证是否存在token
* */
const verifyUseToken = (req, res, next) => {
    // 登录和注册不做校验
    if (req.url === '/user/login' || req.url === '/user/register') {
        // 执行下一个中间件
        return next();
    }
    // 其他rq，需要验证token
    const token = getHeaderToken(req);
    // 不存在token
    if (!token) {
        return res.json({code: -1, message: "请先登录", data: null});
    }

    // 存在token，但在另一地方登录
    if (token) {
        // token失效，默认2小时
        return verifyToken(token, (result) => {
            if (!result.isFlag) {
                res.clearCookie('token');
                return res.json({code: -1, message: "登录凭证失效", data: null});
            }
            const queryData = {id: result.data.id};
            loginSql(queryData, res, results => {
                if (!results.length) {
                    res.clearCookie('token');
                    return res.json({code: -1, message: "用户已注销", data: null});
                }
                if (results[0].token !== token) {
                    res.clearCookie('token');
                    return res.json({code: -1, message: "凭证被重置", data: null});
                }
                return next();
            })
        });
    }
    return next();
}

// 请求超时处理,默认15s
const timeoutMiddleware = (timeoutMs = 15000) => {
    return (req, res, next) => {
        const timeoutTimer = setTimeout(() => {
            res.json(responseResult.error("请求超时"));
        }, timeoutMs)
        res.on("finish", () => {
            clearTimeout(timeoutTimer)
        });
        next();
    }
}

// 不存在路由处理的请求
const noRouter = (req, res, next) => {
    res.json(responseResult.error("Not Server"))
}

/**
 * 参数验证中间件
 * @param value Object 验证的参数数组
 */

const isBodyData = (value) => {
    return (req, res, next) => {
        let v = req.body;
        if (checkParam(value, v)) {
            next();
        } else {
            res.json(responseResult.error('参数错误'))
        }
    }
}

module.exports = {
    verifyUseToken, timeoutMiddleware, noRouter, isBodyData
}
